//
//  HMHealthCounseling.swift
//  HealthMonitoring
//
//  Created by 珠海正杰 on 2018/9/10.
//  Copyright © 2018年 YTYanK. All rights reserved.
//

import UIKit
import SwiftyJSON

/// 咨询选项组件
class OptionItemView: UIView {
    var selectorInt: Int = 0 // 选择项
    var itemH : CGFloat = 30.0
    var btnAry: [UIButton] = []
    var buttonBlock:((Dictionary<String, Any>) ->(Void))?
    init(_ target: Any?, json: JSON) {
        super.init(frame: CGRect.init(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: 30.0))
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
   /**
    *  设置内容
    */
    func setViews(sign: String, json:JSON) {
        let w = UIScreen.main.bounds.size.width - 16.0
        var leW: CGFloat = 0.0   //记录上一个宽度   //左间距宽度 (累计)
        var general: CGFloat = 0.0
        var b: CGFloat = 0.0
        var row: CGFloat = 0.0 // 行
        for (i,item) in json {
            let num =  CGFloat(Int(i)!)
//            if
//            let nameType: AnyClass! = object_getClass(item)
//            print("===??\(nameType)")
            let str = (item["desc"].stringValue) as NSString
            let rect =  String.getTextRectSize(text: str, font: 15, size: CGSize.init(width: w, height: 30.0)) // getTextRectSize(text: str, font: 18, size: CGSize.init(width: w, height: 30.0))
            let btn = UIButton()
        
//            btn.dictionary = ["sign": sign]
            btn.tag = Int(i)!
            btn.dictionary = item.dictionaryObject
            btn.dictionary!["sign"] = sign
            self.addSubview(btn)
           
            
            let  width = rect.width + 15
            b += (width + 10)  //当前这个宽度 + 间距
            if b > w {   //394.0
                b = (width + 10)
                general = 0.0
                row += 1.0
            }else {
                general += leW
            }
           let topH = 30 * row  + ((row != 0.0) ? 10.0 * row : 0.0)

            if num == 0 {
             btn.backgroundColor = configure.shareConfigure.HMColor1
             btn.isSelected = true
            }else {
              btn.backgroundColor = UIColor.white
//                btn.layer.borderColor = configure.shareConfigure.HMColor3.cgColor
             btn.isSelected = false
            }
            btn.titleLabel?.font = UIFont.systemFont(ofSize: 15)
            btn.setTitle(item["desc"].stringValue, for: .normal)
            btn.setTitleColor(UIColor.white, for: UIControlState.selected)
            btn.setTitleColor(UIColor.black, for: .normal)
            btn.topAlign(view: self, predicate: "\(topH)")
            btn.leadingAlign(view: self, predicate: "\(general)")
            btn.heightConstrain(predicate: "\(30)")
            btn.widthConstrain(predicate: "\(width)")
            btn.layer.cornerRadius = 8
            btn.addTarget(self, action: #selector(btnClick(sender:)), for: UIControlEvents.touchUpInside)
//            btn.layer.borderWidth = 1
            
            leW = (width + 10) //记录上一个宽度
             btnAry.append(btn)
        }
        
        itemH = (row + 1) * 30.0 + row * 10.0
    }
    
    
    @objc func btnClick(sender: UIButton) {
        if selectorInt != sender.tag {
             sender.isSelected = !sender.isSelected
            let btn = btnAry[selectorInt]
            btn.isSelected = false
            if btn.isSelected {
                btn.backgroundColor = configure.shareConfigure.HMColor1
            }else {
                btn.backgroundColor = UIColor.white
            }
            
            
            if sender.isSelected {
                sender.backgroundColor = configure.shareConfigure.HMColor1
            }else {
                sender.backgroundColor = UIColor.white
            }
            selectorInt = sender.tag
        }else  {
            
        }
        
            // 获取价格接口
//            NetRequestTool.shareInstance.met = .get
//            NetRequestTool.request(url: "user/consult/estimate", parameters: ["communicateType": "0", "level": String(id)], success: { (json) in
//                print("----->>", json)
//            }, fail: { (code, msg) in
//                print("-======>",msg)
//            }) { }
            
            
            if self.buttonBlock != nil {
                self.buttonBlock!(sender.dictionary!)
            }
    }
}
/// 病情描述的组件
class DescriptionView: UIView, UITextFieldDelegate {
    let w = UIScreen.main.bounds.size.width - (8*4)
    let input = UITextField()
    var imgs: [UIImageView] = []
    var viewH: CGFloat = 150.0
    var vc : UIViewController?
    var inputBlock: ((String) -> ())?

    
    func setViews(json: JSON) {
        self.backgroundColor = UIColor.white
        self.layer.cornerRadius = 8
        self.addSubview(input)
        //HMPhoto.shareInstance.delegate = self
        
        input.delegate = self
        input.leadingAlign(view: self)
        input.trailingAlign(view: self)
        input.topAlign(view: self)
        input.heightConstrain(predicate: "38")
//        input.widthConstrain(predicate: "\(w)")
//        input.backgroundColor = .red
        input.placeholder = "添加病情描述,让医生更好为您服务(选填)"
        
        for i in 0..<3 {
            print("\(i)")
            let leW = CGFloat(i) * (w/3) + 10 //3
            let imagV = UIImageView()
            self.addSubview(imagV)
            imagV.topVertically(view: input)
            imagV.tag = i
            imagV.leadingAlign(view: self , predicate: "\(leW)")
            imagV.widthConstrain(predicate: "\(w/3 - 10)")
            imagV.bottomAlign(view: self)
            imagV.image = UIImage.init(named: "yszs.png")  //imgName(name: "yszs.png")
            imagV.addTapGesture(target: self, action: #selector(imagVClick))
            imgs.append(imagV)
        }
        
        
    }
    
    @objc func imagVClick(tap: UITapGestureRecognizer) {
//        let str = "tap" + String(tap.view!.tag)
         HMPhoto.shareInstance.pushTZImagePickerController(self.vc!, max: 3, column: 4, isSelectOriginal: false)
        HMPhoto.shareInstance.hmImagePickerVc?.didFinishPickingPhotosHandle = {
            (photos: [UIImage]?, assets: [Any]?, isSelectOriginalPhoto: Bool) -> Void in
            var i = 0
            
            HMPhoto.requestImages(photos: photos!)
            
            for item in photos! {
                     print("---->\(i)")
                    self.imgs[i].image = item
                    i += 1
                }
            }
    }
    
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        
        if self.inputBlock != nil {
        self.inputBlock!(textField.text!)
        }
        return true
    }
    
}
/// 计费标准
class FreightBasis: UIView {
    
    let icon = UIImageView()
    let describe = UILabel()
    /// 修改金额
    let modify = UIButton()
    var modifyBlock: ((_ sender: UIButton) -> ())?
    let price = UILabel()
    ///
    let line = UIView()
    var viewH: CGFloat = 80.0
//    var vc: HMHealthCounseling?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setViews()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    func setViews()  {
        self.backgroundColor = UIColor.white
        self.layer.cornerRadius = 8
        
        self.addSubview(icon)
        self.addSubview(describe)
        self.addSubview(modify)
        self.addSubview(price)
        self.addSubview(line)
        
        
        icon.leadingAlign(view: self, predicate: "15")
        icon.centerYAlign(view: self)
        icon.width(view: self , predicate: "*0.15")
        icon.heightConstrain(predicate: "36")
        icon.imgName(name: "freightBasis.png")
        
        describe.centerYAlign(view: self, predicate: "-20")
        describe.leadingHorizontally(view: icon, predicate: "10")
        describe.height(view: self, predicate: "*0.2")
        describe.text = "计费标准"
        describe.textColor = configure.shareConfigure.HMColor1
        describe.font = configure.shareConfigure.HMSize_15

        price.centerYAlign(view: self, predicate: "10")
        price.leadingHorizontally(view: icon, predicate: "10")
        price.text = "预计花费: 15元/15分钟"
        price.font = configure.shareConfigure.HMSize_20
        price.height(view: self, predicate: "*0.4")

        
        line.centerYAlign(view: self)
        line.leadingHorizontally(view: price, predicate: "0")
        line.widthConstrain(predicate: "1")
        line.backgroundColor = configure.shareConfigure.HMColor3
        line.height(view: self, predicate: "*0.6")
        
        
        modify.leadingHorizontally(view: line)
        modify.trailingAlign(view: self, predicate: "-15")
        modify.setTitleColor(configure.shareConfigure.HMColor1, for: .normal)
        modify.setTitle("修改金额", for: .normal)
        modify.addTarget(self, action: #selector(modifyClick), for: UIControlEvents.touchUpInside)
        modify.centerYAlign(view: self)
        
    }
    
    @objc func modifyClick(sender: UIButton) {
        //初始化UITextField
        
        if self.modifyBlock != nil {
            self.modifyBlock!(sender)
        }
        

    }
    
    func setPriceValue (price: String) {
         self.price.text = "预计花费: \(price)元/15分钟"
    }
    


//
    
}


/// 健康咨询
class HMHealthCounseling: HMViewController {
    
//    let search = UITextField()
    let level = UILabel()
    let department = UILabel()
    let mode = UILabel()
    let region = UILabel()
    let fb  = FreightBasis()
    let release = UIButton()
    
    var commTypeList = JSON() // 沟通方式
    var regionList = JSON() //地区
    var levelList = JSON()  //医生级别
    var officeList = JSON() //科室
    
    var selecotRegion = 0
    var selecotLevel = 0
    var selecotOffice =  0
    var priceValue = "15"
    var inputText = ""
    
    // 保存接受到的咨询医生列表
    var doctorList = JSON()
    // 获取发布咨询的ID
    var hcId = ""
    // 计时
    var hcTime:DispatchSourceTimer?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setNavRightView()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        confirm()
    }
    
    
    override func setupView() {
        self.title = "健康咨询"
        
        view.backgroundColor = UIColor.RGBA(r: 239, g: 239, b: 239, a: 1)
        
        view.addSubview(level)
        view.addSubview(department)
        view.addSubview(region)
        let des = DescriptionView()
        des.vc = self
        view.addSubview(des)
        view.addSubview(fb)
        view.addSubview(release)
        
        
        level.topAlign(view: view, predicate: "20")
        level.leadingAlign(view: view)
        level.text = "医生级别"
        let item = OptionItemView(self, json: levelList)
        view.addSubview(item)
        item.setViews(sign: "医生级别",json: levelList)
        let itemH = item.itemH
        item.topVertically(view: level)
        item.leadingAlign(view: view)
        item.trailingAlign(view: view)
        item.heightConstrain(predicate: "\(itemH)")
        item.buttonBlock =  {
            (dic) -> () in
            // 通过医生级别及交流方式获取价格
            let id = dic["id"] as! Int
            // 写死了价格
            var p = "15"
            if id == 0 || id == 1 {
                p = "15"
            }else if id == 2 {
                p = "20"
            }else if id == 3 {
                p = "25"
            }else if id == 4 {
                p = "30"
            }
            self.selecotLevel = id
            self.priceValue = p
            self.fb.setPriceValue(price: p)
        }
        
        
        department.topVertically(view: item, predicate: "20")
        department.leadingAlign(view: view)
        department.text = "选择科室"
        let item1 = OptionItemView(self, json: officeList)
        view.addSubview(item1)
        item1.setViews(sign: "选择科室",json: officeList)
        let itemH1 = item1.itemH
        item1.topVertically(view: department)
        item1.leadingAlign(view: view)
        item1.trailingAlign(view: view)
        item1.heightConstrain(predicate: "\(itemH1)")
        item1.buttonBlock = {
            (dic) -> ()in
             let id = dic["id"] as! Int
             self.selecotOffice = id
        }
        
        
        region.topVertically(view: item1, predicate: "20")
        region.leadingAlign(view: view)
        region.text = "选择医生所在地区"
        let item3 = OptionItemView(self, json: regionList)
        view.addSubview(item3)
        item3.setViews(sign:"选择医生所在地区", json: regionList)
        let itemH3 = item3.itemH
        item3.topVertically(view: region)
        item3.leadingAlign(view: view)
        item3.trailingAlign(view: view)
        item3.heightConstrain(predicate: "\(itemH3)")
        item3.buttonBlock = {
            (dic) -> () in
            
            let id = dic["id"] as! Int
            self.selecotRegion = id
        }
        
      
        des.setViews(json: nil)
        des.topVertically(view: item3, predicate: "20")
        des.leadingAlign(view: view)
        des.trailingAlign(view: view)
        des.heightConstrain(predicate: "\(des.viewH)")
        des.inputBlock = {
            (text) -> () in
            self.inputText = text
//            print("----\(text)")
            
        }
        
        fb.topVertically(view: des)
        fb.leadingAlign(view: view)
        fb.trailingAlign(view: view)
        fb.heightConstrain(predicate: "\(fb.viewH)")
        fb.modifyBlock = {
            (sendr : UIButton) -> () in

            var inputText = UITextField()
          
            
            let msgAlertCtr = UIAlertController.init(title: nil, message: "请输入修改的金额", preferredStyle: .alert)
            let ok = UIAlertAction.init(title: "确定", style:.default) { (action:UIAlertAction) ->() in
                if((inputText.text) != ""){
                     let text = inputText.text
                    if Int(text!)! < 1 {
                        self.showToast(message: "请金额不能小于1元")
                    }else {
                        self.priceValue = text!
                         self.fb.setPriceValue(price: text!)
                    }
                }
            }
    
            let cancel = UIAlertAction.init(title: "取消", style:.cancel) { (action:UIAlertAction) -> ()in  }
            msgAlertCtr.addAction(ok)
            msgAlertCtr.addAction(cancel)
            //添加textField输入框
            msgAlertCtr.addTextField { (textField) in
                //设置传入的textField为初始化UITextField
                inputText = textField
                inputText.delegate = self
                inputText.placeholder = "请输入金额"
            }
            //设置到当前视图
            self.present(msgAlertCtr, animated: true, completion: nil)
        }
   
        
//        let v = UIView.creatorProtocolButton(target: self, text: "我同意", btnText: "《乐众康支付协议》", font: 15, btnAction: #selector(btnClcik), iconAction: #selector(iconAction))
//        view.addSubview(v)
//
//        v.topVertically(view: fb)
////        v.leadingAlign(view: view, predicate: "2")
//        v.centerXAlign(view: view)
////        v.trailingAlign(view: view)
//        v.heightConstrain(predicate: "30")
//        v.backgroundColor = .red
       
        release.topVertically(view: fb, predicate: "20")
        release.leadingAlign(view: view)
        release.trailingAlign(view: view)
        release.heightConstrain(predicate: "44")
        release.setTitle("确认发布", for: .normal)
        release.addTarget(self, action: #selector(releaseClick), for: UIControlEvents.touchUpInside)
        release.setTitleColor(UIColor.white, for: .normal)
        release.backgroundColor = configure.shareConfigure.HMColor1
        release.layer.cornerRadius = 6 
        

        
    }
    
    
    ///
    func setNavRightView()  {
        let setBtn =  UIButton(frame: CGRect(x: 0, y: 0, width: 24, height: 24))
        setBtn.setTitle("历史发布", for: .normal)
        setBtn.setTitleColor(configure.shareConfigure.HMColor1, for: .normal)
        let rightBtn = UIBarButtonItem(customView: setBtn)
        setBtn.addTarget(self, action: #selector(navRightBtn), for: UIControlEvents.touchUpInside)
        let negativeSpacer = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
        negativeSpacer.width = -10
        
        navigationItem.rightBarButtonItems = [negativeSpacer, rightBtn]
    }
    
    @objc func navRightBtn(sender: UIButton) {
        // 进入历史发布
        NetRequestTool.shareInstance.met = .get
        NetRequestTool.request(url: "user/consult/history", parameters: [:], success: { (json) in
            let rh = HMReleaseHistory()
            rh.rhJsonData = json["data"]
            self.pushViewController(rh)
        }, fail: { (code, msg) in
            print("请求失败\(msg)")
        }) {}
        
    
       
    }
    
    
    @objc func releaseClick(sender: UIButton) {

        // 这个没清理
        let url = HMPhoto.shareInstance.urls
        
        var par = Dictionary<String, Any>()
        par["level"] = self.selecotLevel
        par["office"] = self.selecotOffice
        par["communicateType"] = 0
        par["region"] = self.regionList[selecotRegion]["desc"].stringValue
        par["desc"] = self.inputText
        par["cost"] = self.priceValue
        par["images"] = url
        
        NetRequestTool.shareInstance.met = .post
        NetRequestTool.requestForJSON(url: "user/consult", parameters: par, success: { (json) in
           
            
            let code = json["data"]["code"].intValue
            if code == 0 {
                let idStr = json["data"]["consultId"].stringValue
                
                // 进入邀请列表
                let al = HMAcceptanceList()
                al.consultId = idStr   // 发布的健康咨询ID
                self.pushViewController(al)
                
                
                // 发布的ID存在，代表可以进入咨询列表
                UserDefaults.standard.set(idStr, forKey: "consultId")
                let strDate = Date.getCurrentDate()
                // 发布时间次
                UserDefaults.standard.set(strDate, forKey: "consultTime")
                //            self.firingTimeCount(count: 1800, operate: { (timer, timerCount) in
                //                print("=========>>>\(timerCount)")
                //                if timerCount == 0 {
                //                    UserDefaults.standard.removeObject(forKey: "consultId")
                //                }
                //            })
            }else if code == 1001 { // code == 1001 信誉值不足，发布失败
               print("1001 信誉值不足，发布失败")
            }else {
               print("其他原因")
            }
            


        }, fail: { (code, msg) in
            self.showToast(message: msg)
        }) {}

    }

    /// 提示选择框
    func confirm() {
        // 获取创建
        let strDate =  UserDefaults.standard.string(forKey: "consultTime")
        if strDate != nil  {
            let date = Date.getTimeDifferentWith(date: strDate!)
            if date.contains("时") {
                UserDefaults.standard.removeObject(forKey: "consultTime")
                 UserDefaults.standard.removeObject(forKey: "consultId")
            }else {
                let difference: Int = Int(String.suffixString(value: date, character: "分"))!
                if difference >= 30 {
                    UserDefaults.standard.removeObject(forKey: "consultTime")
                    UserDefaults.standard.removeObject(forKey: "consultId")
                }else {
                    if  UserDefaults.standard.string(forKey: "consultId") != nil {
                        self.showConfirm(title: "温馨提示！", message: "你当前已发布咨询,是否进入咨询列表！", confirmText: "取消", cancelText: "进入", onConfirm: {
                            
                        }, onCancel: {
                            let al = HMAcceptanceList()
                            al.consultId =  UserDefaults.standard.string(forKey: "consultId")!
                            self.pushViewController(al)
                        })
                    }
                }
            }
            
         
        }
        
        
        
        
   
    }
    
}


extension HMHealthCounseling: UITextFieldDelegate {
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let text = textField.text!
        let len = text.count + string.count - range.length
        
        // 限制输入内容，为数字
        let length = string.lengthOfBytes(using: String.Encoding.utf8)
        for loopIndex in 0..<length {
            let char = (string as NSString).character(at: loopIndex)
            if char < 48 { return false }
            if char > 57 { return false }
        }
        return (len <= 2)
    }
}
